package org.realogic.cfm.common.collection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * 树-创建者
 */

public final class TreeFactory<T extends TreeEntity> {
	/*
	 * TreeEntity List,List集合中的数据没有任何顺序约定
	 */
	private List<T> entityList;

	/*
	 * 根节点Key值
	 */
	private String rootKeyVale = "";

	public TreeFactory(List<T> entityList_) {
		this.entityList = entityList_;
	}

	public String getRootKeyVale() {
		return rootKeyVale;
	}

	public void setRootKeyVale(String rootKeyVale) {
		this.rootKeyVale = rootKeyVale;
	}

	/*
	 * 创建树,返回树根节点
	 */
	public TreeNode<T> create() {
		List<TreeNode<T>> treeNodeList = convert();
		if (treeNodeList == null || treeNodeList.isEmpty()) {
			return null;
		}
		int size = treeNodeList.size();
		Map<String, TreeNode<T>> tmpMap = new HashMap<String, TreeNode<T>>((size + 1) * 4 / 3);
		TreeNode<T> root = null;
		for (int i = 0; i < size; i++) {
			TreeNode<T> tmpNode1 = treeNodeList.get(i);
			tmpMap.put(tmpNode1.getNodeID(), tmpNode1);
			if (rootKeyVale.equals(tmpNode1.getParentID())) {
				root = tmpNode1;
				tmpNode1.setLevel(1);
			}
		}
		TreeNode<T> tmpNode1 = null;
		TreeNode<T> tmpNode2 = null;
		for (int i = 0; i < size; i++) {
			tmpNode1 = treeNodeList.get(i);
			if (tmpNode1 != null) {
				tmpNode2 = tmpMap.get(tmpNode1.getParentID());
			}
			if (tmpNode1 != null && tmpNode2 != null) {
				tmpNode2.addChild(tmpNode1);
			}
		}
		tmpMap.clear();
		tmpMap = null;
		return root;
	}

	/*
	 * 转换成TreeNode List
	 */
	private List<TreeNode<T>> convert() {
		if (entityList == null || entityList.isEmpty()) {
			return null;
		}
		int size = entityList.size();
		List<TreeNode<T>> tmpList = new ArrayList<TreeNode<T>>(size);
		TreeNode<T> tmpNode = null;
		String key = null;
		String parentKey = null;
		T tmpTreeEntity = null;
		for (int i = 0; i < size; i++) {
			tmpTreeEntity = entityList.get(i);
			key = tmpTreeEntity.getKey();
			// ParentKey为空,挂在根节点下
			parentKey = tmpTreeEntity.getParentKey() == null ? rootKeyVale : tmpTreeEntity.getParentKey();
			tmpNode = new TreeNode<T>(key, parentKey);
			tmpNode.setInformation(tmpTreeEntity);
			tmpList.add(tmpNode);
		}
		return tmpList;
	}

	/*
	 * 遍历树-简单示例
	 */
	public void traverse(TreeNode<TreeEntity> node) {
		TreeEntity temp = node.getInformation();
		System.out.println("key:" + temp.getKey() + ";parentKey:" + temp.getParentKey() + ";level:" + temp.getTreeLevel());
		if (node.getChildrenSize() > 0) {
			for (int i = 0; i < node.getChildrenSize(); i++) {
				TreeNode<TreeEntity> tn = node.getChild(i);
				traverse(tn);
			}
		}
	}
}